Welcome to pandas!

6.2 分层索引的设置

项目

创建时 已存在时 分层索引标题</p>

Series分层索引

index参数 index属性 index.names属性

DateFrame行分层索引

index参数 index属性 index.names属性

DateFrame列分层索引

columns参数 columns参数 culmns.names属性</p>

1、创建时指定Series索引

import pandas as pd

l=[[ "A组","A组","B组","B组" ],[ "1","2","3","4" ]]

s=pd.Series([ "张三","李四","王麻子","小曾" ], index =l)

print (s)

返回:

A组 1 张三
2 李四
B组 3 王麻子
4 小曾

dtype: object


import pandas as pd

l=[[ "A组","A组","B组","B组" ],[ "1","2","3","4" ]]

s=pd.Series([ "张三","李四","王麻子","小曾" ], index =l)

s.index.names=[ "组名","工号" ] #索引标题["组名","工号"]

print (s)

返回:

组名 工号
A组 1 张三
2 李四
B组 3 王麻子
4 小曾

dtype: object


2、重置已存在Series索引

import pandas as pd

l=[[ "A组","A组","B组","B组" ],[ "1","2","3","4" ]]

s=pd.Series([ "张三","李四","王麻子","小曾" ]) #如Series是通过切片生成

s.index=l #如Series是通过切片生成,则可以通过s.index指定索引

s.index.names=[ "组名","工号" ] #指定索引标题["组名","工号"]

print (s)

返回结果和上列是一样的。


3、DataFrame行索引

import pandas as pd,numpy as np

l=[[ "A组","A组","B组","B组" ],[ "1","2","3","4" ]]

arr=np.arange( 2000,2020 ).reshape( 4,5 )

df=pd.DataFrame(arr, index =l)

df.index.names=[ "组名","工号" ]

print (df)

返回:

0 1 2 3 4
组名 工号
A组 1 2000 2001 2002 2003 2004
2 2005 2006 2007 2008 2009
B组 3 2010 2011 2012 2013 2014
4 2015 2016 2017 2018 2019

4、DataFrame列索引

import pandas as pd,numpy as np

l=[[ "A组","A组","B组","B组","C组" ],[ "1","2","3","4","5" ]]

arr=np.arange( 2000,2020 ).reshape( 4,5 )

df=pd.DataFrame(arr, columns =l)

df.columns.names=[ "组名","工号" ]

print (df)

返回:

组名 A组 B组 C组
工号 1 2 3 4 5
0 2000 2001 2002 2003 2004
1 2005 2006 2007 2008 2009
2 2010 2011 2012 2013 2014
3 2015 2016 2017 2018 2019